import json
import random
import time

from exception.api_exception import APIException
from dao import work_order_dao, work_order_extend_dao
import traceback
import model.model as ut
import utils.wjx.wjx_explain_v2 as wjx_explain_v2
from utils.credamo import credamo_explain
from utils.gg import gg_explain
from utils.qualtrics import qualtrics_explain
from utils.wjw import wjw_explain
from utils.tx import tx_explain
import requests


def explain_link_v3(work_order_id: int):
    cur_work_order = work_order_dao.query_work_order_by_id(work_order_id)
    title_maps, titles = explain_link_v3_by_link(cur_work_order.link)
    work_order_extend_dao.delete_result_by_word_order_id(work_order_id=work_order_id)
    work_order_extend_dao.batch_insert(
        [ut.WorkOrderExtend(work_order_id=work_order_id, titles=titles, title_maps=title_maps)])
    return {'list': title_maps, 'data_index': titles, 'total_data_index': len(titles)}


def explain_link_v3_by_link(cur_link):
    if cur_link.startswith('https://www.wenjuan.com'):  # 问卷网开头就执行问卷网的代码
        title_maps, titles = _sys_explain_wjw(cur_link)
    elif cur_link.startswith('https://wj.qq.com'):  # 腾讯问卷开头就执行腾讯问卷的代码
        title_maps, titles = _sys_explain_tx(cur_link)
    elif cur_link.startswith('https://docs.google.com/'):  # 谷歌问卷
        title_maps, titles = _sys_explain_gg(cur_link)
    elif 'qualtrics.' in cur_link or 'q.surveys.' in cur_link:  # qualtric问卷
        title_maps, titles = _sys_explain_qualtrics(cur_link)
    elif 'credamo.com' in cur_link:  # 见数
        title_maps, titles = _sys_explain_credamo(cur_link)
    else:
        title_maps, titles = _sys_explain_wjx(cur_link)
    return title_maps, titles


def _sys_explain_qualtrics(link: str):
    """qualtric问卷解析结果"""
    obj = qualtrics_explain.QualtricsExplain(link)
    explain_res = obj.do_explain()
    if not explain_res:
        return "", ""
    return explain_res.get('list'), explain_res.get('data_index')


def _sys_explain_credamo(link: str):
    """credamo问卷解析结果"""
    obj = credamo_explain.CredamoExplain(link)
    explain_res = obj.do_explain()
    if not explain_res:
        return "", ""
    return explain_res.get('list'), explain_res.get('data_index')


def _sys_explain_gg(link: str):
    """谷歌问卷解析结果"""
    obj = gg_explain.GgExplain(link)
    explain_res = obj.do_explain()
    if not explain_res:
        return "", ""
    return explain_res.get('list'), explain_res.get('data_index')


def _sys_explain_tx(link: str):
    """腾讯问卷解析结果"""
    obj = tx_explain.TxExplain(link)
    explain_res = obj.do_explain()
    if not explain_res:
        return "", ""
    return explain_res.get('list'), explain_res.get('data_index')


def _sys_explain_wjw(link: str):
    obj = wjw_explain.WjwExplain(link)
    explain_res = obj.do_explain()
    if not explain_res:
        return "", ""
    return explain_res.get('list'), explain_res.get('data_index')


def _sys_explain_wjx(cur_link):
    def pre_explain(link: str):
        success = False
        header = dict()
        header['upgrade-insecure-requests'] = '1'
        header['X-Forwarded-For'] = f'{112}.{random.randint(64, 68)}.{random.randint(0, 255)}.{random.randint(0, 255)}'
        header['user-agent'] = \
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
        header['accept'] = ('text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,'
                            'image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9')
        header['sec-fetch-site'] = 'none'
        header['sec-fetch-mode'] = 'navigate'
        header['sec-fetch-user'] = '?1'
        header['sec-fetch-dest'] = 'document'
        header['accept-encoding'] = 'gzip, deflate, br'
        header['accept-language'] = 'zh-CN,zh'
        response = requests.get(link, allow_redirects=False, headers=header, timeout=10)
        if response.status_code == 200:
            success = True
        elif response.status_code == 302:  # 请求的资源需要重定向
            raise APIException(message="链接已被重定向，请检查问卷链接是否跳转到新的链接或已关闭")
            # headers = response.headers
            # # 遍历打印每个头字段及其值
            # for key, value in headers.items():
            #     if str.lower('Location') == str.lower(key):
            #         real_link = str(value)
        elif response.status_code == 404:  # 请求的资源不存在
            raise APIException(message="请求的链接不存在")
        else:  # 其他状态码处理
            pass
        return success

    try:
        is_success = pre_explain(cur_link)  # 预解析链接
        if not is_success:
            raise APIException(message="问卷预解析失败")
        title_maps, titles = wjx_explain_v2.explain_www_wjx_cn(cur_link)
    except Exception as e:
        traceback.print_exc()
        raise APIException(message="文件解析失败->" + str(e))
    return title_maps, titles
